<?php
namespace app\index\controller;

use think\Controller;
use app\index\controller\Token;
use think\facade\Cache;

class Base extends Controller
{
    protected $no_login = ['admin/login'];   //不需要验证的接口

    public function initialize()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        $path =  $this->request->path();
        if (!in_array($path, $this->no_login)) {
            try {
                $userId = Token::getUserId();
                if (empty($userId)) {
                    $this->errMsg('token验证失败', null, 403);
                } else {
                    Cache::set('userId', $userId, 3600);
                }
            } catch (\Throwable $e) {
                //throw $e;
                $this->errMsg('token验证失败', null, 403);
            }
        }
    }
    /**
     * 分页注释
     *
     * @param integer $totalNum
     * @return void
     */
    protected function pagination($total = 0, $data)
    {
        $res =[
            'success' => true,
            'data'  => $data,
            'total'  =>$total,
            'msg' => '查询成功'
        ];

        echo json_encode($res, JSON_UNESCAPED_UNICODE);
        die;
    }
    /**
     * 返回成功信息
     *
     * @param string $msg
     * @param [type] $data
     * @return void
     */
    protected function okMsg($msg='', $data)
    {
        $res = [
            'success' => true,
            'data'  => $data,
            'msg'  => $msg
        ];
        echo json_encode($res, JSON_UNESCAPED_UNICODE);
        die;
        //return json($res)->send();
    }
    /**
     * 错误信息
     *
     * @param string $msg
     * @param [type] $data
     * @return void
     */
    protected function errMsg($msg='', $data=null, $status='')
    {
        $res =[
            'success' => false,
            'status'=>$status,
            'data'  => $data,
            'msg'  => $msg
        ];
        
        echo json_encode($res, JSON_UNESCAPED_UNICODE);
        die;
        // return json($res)->send();
    }
    protected function getOffset($pageNo,$pageSize){
        $pageNoTemp = (int)($pageNo);
        $pageSizeTemp = (int)($pageSize);

        return ($pageNoTemp-1)*$pageSizeTemp;
    }
}
